//
//  StoreListVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/3.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class StoreListVC: BaseViewControllerWithHeader,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    var isSetting = false
    var isChange = false
    var colltionView : UICollectionView?
    var dataArr = [[String : Any?]]()
    var curIndexPath : IndexPath?
    
    let switchMallOnSelected : Bool
    init(switchMallOnSelected : Bool) {
        self.switchMallOnSelected = switchMallOnSelected
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        getdataList()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    func getdataList() {
        let identityToken = LocalStorage.getString(forKey: USER_IDENTITYTOKEN)
        
        let params :[String:Any] = ["identityToken":identityToken ?? ""]
        
        MBProgressHUD.showOrIncrease()
        API.request(url: .S_StoreList, params: params) { (result) in
            
            if result.success {
               MBProgressHUD.hideOrDecrease()
               if let dl = result.data?.getDictList("data") {
                   for item in dl {
                    self.dataArr.append(item)
                   }
                   self.queryData()
               }
            }else{
                MBProgressHUD.hideOrDecrease()
                let popup = PopupSureBox(title: result.errMsg ?? "登录失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    func setMall() {
        let identityToken = LocalStorage.getString(forKey: USER_IDENTITYTOKEN)
        let dic = dataArr[curIndexPath!.row]
        
        let params :[String:Any] = ["identityToken":identityToken ?? "",
                                    "mallID":dic.getString("mallID") ?? ""]
        MBProgressHUD.showOrIncrease()
        
        API.request(url: .S_SetMall, params: params) { (result) in
            if result.success {
               MBProgressHUD.hideOrDecrease()
               LocalStorage.saveDic(dic, forKey: USER_DEFULT_MALL)
               let popup = PopupBox(infoText: "设置成功")
               popup.show(vc: UIViewController.topMostController() ?? self)
                if self.switchMallOnSelected {
                    self.switchMall()
                }
            }else{
                MBProgressHUD.hideOrDecrease()
                let popup = PopupSureBox(title: result.errMsg ?? "处理失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                }
            }
        }
    }

        
    func switchMall() {
        let identityToken = LocalStorage.getString(forKey: USER_IDENTITYTOKEN)
        let dic = dataArr[curIndexPath!.row]
        
        let params :[String:Any] = ["identityToken":identityToken ?? "",
                                    "mallID":dic.getString("mallID") ?? ""]
        MBProgressHUD.showOrIncrease()
        
        API.request(url: .S_SwitchMall, params: params) { (result) in
            if result.success {
               MBProgressHUD.hideOrDecrease()
                self.getMall()
            }else{
                MBProgressHUD.hideOrDecrease()
                let popup = PopupSureBox(title: result.errMsg ?? "处理失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                }
            }
        }
    }
    
    
    //获取当前用户商城有则直接进入，没有跳到商城选择
    func getMall() {
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        
        API.request(url: .S_GetMall, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success,let dl = result.data?.getDictionary("data") {
                LocalStorage.saveDic(dl, forKey: DEFULT_MALL)
                self.sendNot()
                self.getUserInfoForBackstage(guid: LocalStorage.getString(forKey: USER_GUID)!, token: LocalStorage.getString(forKey: USER_IDENTITYTOKEN)!, mallId: dl.getString("mallID") ?? "")
                
                if self.isSetting {
                    self.popViewController(vCount: 3)
                    (UIApplication.shared.delegate as? AppDelegate)?.changeMall()
                }
                else {
                    self._popViewController(animated: false)
                    let vc = MainTabBarController()
                    UIViewController.topMostController()?.pushViewController(vc)
//                    self.pushViewController(vc)
                }
            }
            else {
            }
        }
    }

    func sendNot() {
        let noT = NSNotification.Name(rawValue: MALL_CHANGE)
        let dic = ["key":"value"]
        NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
    }
    
    //中台信息同步
    func getUserInfoForBackstage(guid: String,token: String,mallId: String) {
        let params = ["guid": guid,
                      "token": token,
                      "mallId": mallId]
        API.formRequest(url: .YI_GetUserInfoForBackstage, params: params, callback: { r in
            if r.success {
                print("中台信息同步成功...")
            }
        })
    }
}

// MARK:- UI
extension StoreListVC {
    func setupUI() {
        headTitle.text = "选择商城"
        
        let layout = UICollectionViewFlowLayout()
        layout.sectionInset = .init(top: 10, left: 30, bottom: 10, right: 30)
        colltionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        colltionView!.register(StoreListCell.self, forCellWithReuseIdentifier:"cell")
        colltionView?.delegate = self;
        colltionView?.dataSource = self;
        colltionView?.backgroundColor = .white
        //设置每一个cell的宽高
        layout.itemSize = CGSize(width: 95, height: 121)
        self.safeView.addSubview(colltionView!)
        colltionView?.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-100)
        }
        
        let okbtn = safeView.drawButton(title: "确认选择", titleColor: .white, fontSize: 14) { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-30)
            make.width.equalTo(315)
            make.height.equalTo(35)
        }
        okbtn.backgroundColor = .xFC4C02
        okbtn.addTarget(self, action: #selector(onSubmitButtonClick(button:)), for: .touchUpInside)
    }
}

// MARK:- 事件
extension StoreListVC {
    
    @objc func onSubmitButtonClick(button:UIButton){
        if curIndexPath != nil {
            if isChange {
                switchMall()
            }
            else {
                setMall()
            }
        }
        else {
            let popup = PopupSureBox(title: "请选择商城", infoText: "", sureText: "确定")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
                //确定执行
            }
        }
    }
    
    func queryData() {
        colltionView?.reloadData()
        for i in 0...dataArr.count-1 {
            let mallID = dataArr[i].getString("mallID")
            var dic = LocalStorage.getDic(forKey: USER_DEFULT_MALL)
            if isChange {
                dic = LocalStorage.getDic(forKey: DEFULT_MALL)
            }
            let defaultLoginMall = dic?.getString("mallID")
            if mallID == defaultLoginMall {
                colltionView?.selectItem(at: .init(row: i, section: 0), animated: false, scrollPosition: .top)
            }
        }
    }
    
    ///UICollectionViewDelegate
    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    //返回多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArr.count
    }
    //返回自定义的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! StoreListCell
//         cell.titleLabel?.text = "wangjie"
        let dic = dataArr[indexPath.row]
        cell.celldata = StoreListCellModel(fromDictionary: dic as [String : Any])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        curIndexPath = indexPath
    }
}
